
/**
 * 加载TREEGRID扩展模块
 * 
 * @auth liangpingzheng
 * @date 2018-03-09
 */
layui.extend({
    treeGird: '../layui/lay/modules/treeGird'
});

/**
 *	菜单管理
 *	@auth liangpingzheng
 *	@date 2018-02-27
 */
layui.use(['form', 'tree', 'layer', 'laytpl', 'treeGird'], function () {
    var layer = parent.layer === undefined ? layui.layer : top.layer,
            form = layui.form,
            layedit = layui.layedit,
            laytpl = layui.laytpl,
            treeGird = layui.treeGird,
            $ = layui.$;

    /**
     * 设置表头
     */
    var layout =
            [{name: 'ID',
                    headerClass: 'value_col',
                    colClass: 'value_col',
                    style: 'width: 5%',
                    render: function (row) {
                        return row.id;
                    }
                },
                {
                    name: '菜单名称',
                    treeNodes: true,
                    headerClass: 'value_col',
                    colClass: 'value_col',
                    style: '25%',
                    render: function (row) {
                        return row.title;
                    }
                },
                {
                    name: '图标',
                    headerClass: 'value_col',
                    colClass: 'value_col',
                    style: 'width: 10%',
                    render: function (row) {
                        return '<i class="larry-icon ' + row.icon + '" data-icon="' + row.icon + '" data-font="larry-icon"></i>';
                    }
                },
                {
                    name: '类型',
                    headerClass: 'value_col',
                    colClass: 'value_col',
                    style: 'width: 5%;min-width:50px;',
                    render: function (row) {
                        var cls = "";
                        if (row.type == 1) {
                            //模块
                            cls = "layui-btn-normal";
                            type_name = "模块";
                        } else if (row.type == 2) {
                            //导航
                            cls = "layui-btn-danger";
                            type_name = "导航";
                        } else if (row.type == 3) {
                            //菜单
                            cls = "layui-btn-warm";
                            type_name = "菜单";
                        } else if (row.type == 4) {
                            //节点
                            cls = "";
                            type_name = "节点";
                        }
                        return '<span class="layui-btn ' + cls + ' layui-btn-xs">' + type_name + '</span>';
                    }
                },
                {
                    name: '菜单URL',
                    headerClass: 'value_col',
                    colClass: 'value_col',
                    style: 'width: 10%;min-width:250px;',
                    render: function (row) {
                        return (row.url && row.type == 4) ? row.url : '';
                    }
                },
                {
                    name: '权限标识',
                    headerClass: 'value_col',
                    colClass: 'value_col',
                    style: 'width: 8%;min-width:150px;',
                    render: function (row) {
                        return row.auth ? row.auth : '';
                    }
                },
                {
                    name: '状态',
                    headerClass: 'value_col',
                    colClass: 'value_col',
                    style: 'width: 5%;min-width:50px;',
                    render: function (row) {
                        return (row.is_show == 1 ? '<span class="layui-btn layui-btn-normal layui-btn-xs">显示</span>' : '<span class="layui-btn layui-btn-normal layui-btn-xs layui-btn-danger">不显示</span>');
                    }
                },
                {
                    name: '是否公共',
                    headerClass: 'value_col',
                    colClass: 'value_col',
                    style: 'width: 5%;min-width:60px;',
                    render: function (row) {
                        return row.is_public == 1 ? "是" : "否";
                    }
                },
                {
                    name: '排序',
                    headerClass: 'value_col',
                    colClass: 'value_col',
                    style: 'width: 5%;min-width:50px;',
                    render: function (row) {
                        return row.sort_order;
                    }
                },
                {
                    name: '操作',
                    headerClass: 'value_col',
                    colClass: 'value_col',
                    style: 'width: 20%;min-width:180px;text-align:center;',
                    render: function (row) {
                        return '<a class="layui-btn layui-btn-xs layui-btn-normal btnAdd2" lay-event="edit" data-id="' + row.id + '"><i class="layui-icon">&#xe654;</i>添加</a>' +
                                '<a class="layui-btn layui-btn-xs btnEdit" lay-event="edit" data-id="' + row.id + '"><i class="layui-icon">&#xe642;</i>编辑</a>' +
                                '<a class="layui-btn layui-btn-xs layui-btn-danger btnDel" lay-event="del" data-id="' + row.id + '"><i class="layui-icon">&#xe640;</i>删除</a>';
                    }
                }];

    /**
     * 获取数据列表
     */
    var getMenuList = function () {

        var result;
        // 设置同步
        $.ajaxSetup({
            async: false
        });

        $.post(aUrl, {}, function (data) {
            if (data.success) {
                result = data.data;
            } else {
                //TODO...
            }

        }, 'json');

        // 恢复异步
        $.ajaxSetup({
            async: true
        });

        return result;
    }

    /**
     * 渲染TREE列表
     */
    var treeIns = layui.treeGird({
        elem: '#treeList', //传入元素选择器
        spreadable: false, //设置是否全展开，默认不展开
        checkbox: true,
        nodes: getMenuList(),
        layout: layout
    });
    form.render();

    /**
     * 全部收缩
     */
    $('#collapse').on('click', function () {
        layui.collapse(treeIns);
    });

    /**
     * 全部展开
     */
    $('#expand').on('click', function () {
        layui.expand(treeIns);
    });

    /**
     * 行选中事件
     */
    form.on('checkbox(*)', function (data) {
        console.log(data.elem); //得到checkbox原始DOM对象
        console.log(data.elem.checked); //是否被选中，true或者false
        console.log(data.value); //复选框value值，也可以通过data.elem.value得到
        console.log(data.othis); //得到美化后的DOM对象

        var arr = layui.getSelected(treeIns);
        console.log(arr.length)
    });

    /**
     * 监听状态开关操作
     */
    form.on('switch(is_public)', function (obj) {
        //layer.tips(this.value + ' ' + this.name + '：' + obj.elem.checked, obj.othis);
    });

    /**
     * 监听指定开关
     */
    form.on('switch(is_show)', function (data) {
//        layer.msg('开关checked：' + (this.checked ? 'true' : 'false'), {
//            offset: '6px'
//        });
        // layer.tips('温馨提示：请注意开关状态的文字可以随意定义，而不仅仅是ON|OFF', data.othis)
    });

    /**
     * 搜索列表
     */
    $(".btnSearch").on("click", function () {
        if ($(".searchVal").val() != '') {
            table.reload("test", {
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                    key: $(".searchVal").val()  //搜索的关键字
                }
            })
        } else {
            layer.msg("请输入搜索的内容");
        }
    });

    /**
     * 添加菜单
     */
    $(".btnAdd").click(function () {
        edit(0, 0);
    });

    $(".btnAdd2").click(function () {
        var pid = $(this).attr("data-id");
        edit(0, pid);
    });

    $(".btnEdit").click(function () {
        var id = $(this).attr("data-id");
        edit(id, 0)
    });

    $(".btnDel").click(function () {
        var id = $(this).attr("data-id");
        var obj = $(this).parent().parent();
        del(id, obj);
    });

    /**
     * 添加或编辑
     */
    function edit(id, pid) {

        var title = '新增菜单';
        if (id > 0) {
            title = '修改菜单';
        }
        var index = layui.layer.open({
            title: title,
            type: 2,
            area: ["770px", "520px"],
            content: "/manager/menu/edit?id=" + id + "&pid=" + pid,
            success: function (layero, index) {
                //TODO...
                setTimeout(function () {
                    layer.tips('点击此处返回列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                }, 500)
            },
        });

    }

    /**
     * 删除
     */
    function del(id, obj) {

        layer.confirm('您确定要删除吗？删除后将无法恢复！', function (index) {
            layer.close(index);
            layui.$.ajax({
                url: "/manager/menu/drop",
                dataType: "json",
                type: "POST",
                data: {"id": id},
                beforeSend: function () {
                    layer.msg('正在删除。。。', {
                        icon: 16
                        , shade: 0.01
                        , time: 0
                    });
                },
                success: function (res) {
                    if (res.success) {
                        //2秒后关闭
                        layer.msg(res.msg, {icon: 1, time: 1000}, function () {
                            obj.remove();
                        });
                    } else {
                        layer.msg(res.msg, {icon: 5});
                    }
                }
            });

        });

    }

    /**
     * 监听表单并提交
     */
    form.on('submit(submitForm)', function (data) {

        var index = layer.msg('数据提交中，请稍候', {icon: 16, time: false, shade: 0.2});
        $.post(aUrl, data.field, function (data) {
            if (data.success) {
                layer.close(index);
                layer.msg("保存成功！");
                layer.closeAll("iframe");
                var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                parent.layer.close(index); //再执行关闭
                //刷新父页面
//                parent.location.reload();

                return false;
            } else {
                layer.close(index);
                layer.msg(data.msg);
            }
        }, 'json');

        return false;
    });

    /**
     * 选择图标
     */
    $(".btnIcon").click(function () {
        var index = layui.layer.open({
            title: "选择系统图标",
            type: 2,
            area: ["770px", "560px"],
            content: "/manager/menu/geticon",
            success: function (layero, index) {
                //TODO...
                setTimeout(function () {
                    layer.tips('点击此处返回列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                }, 500)
            },
        });
    });

//自动填写权限码
    $('#url').blur(function () {
        console.log(this.value);
        url = this.value;
        if (url) {
//            auth = url.replace('/',':');
            if (url.slice(0, 1) === '/') {
                url = url.slice(1);
            }
            auth = url.replace(new RegExp("/", "gm"), ":");
            $("#auth").val(auth);

        }
    });

});
